/**
 * Loads specified "select" element via ajax
 */
$.fn.datamap = function(params){
	params = (params != undefined)? params:{};
	var options = {};
	
	options.url  = (params.url != undefined)? params.url:false;
	options.data = (params.data != undefined)? params.data:{};
	options.relation = (params.relation != undefined)? params.relation:false;
	options.event = (params.event != undefined)?params.event : 'change';
	options.tag = (params.tag != undefined)?params.tag : 'option';
	options.contextAttr = (params.contextAttr != undefined)?params.contextAttr : 'value';
	/* Could be 'replace|append|prepend' */
	options.insertType = (params.insertType != undefined)?params.insertType : 'replace';
	options.data.identifier = (params.identifier != undefined)?params.identifier : -1;
	
	/* Binding events */
	return this.each(function(){
		var related = $(options.relation);
		$(this).bind(options.event, function(e){
			var appendData = "";
			var i = 0;
			/* Collecting data to send */
			options.data.identifier = $(this).val();
			
			/* Loading data */
			$.getJSON(
				options.url,
				options.data,
				function(data){
					for(i in data){
						appendData += "<"+options.tag+" "+options.contextAttr+"='"+data[i].id+"'>"+data[i].name+"</"+options.tag+">";
					};
					switch(options.insertType){
						case "prepend":
							related.prepend(appendData);
						break;
						case "append":
							related.append(appendData);
						break;
						default:
							related.empty().append(appendData);
						break;
					}
				}
			);
		});
	});
};